package org.jpass.dc.business.project.logic;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.tools.ant.Project;
import org.jpass.dc.business.conpiler.CompileProject;
import org.jpass.dc.business.project.bean.CProject;
import org.jpass.dc.business.project.dao.ProjectDao;
import org.jpass.dc.business.user.bean.UserVOBean;
import org.jpass.dc.common.bean.Page;
import org.jpass.dc.common.bean.TreeNode;
import org.jpass.dc.common.exception.ApplicationException;
import org.jpass.dc.common.exception.IDEBuildException;

/**
 * 处理项目的业务类
 * @author WeiLong Peng
 *
 */
public class ProjectService {
	private FileService fs = new FileService();
	
	private ProjectDao projectDao = new ProjectDao();
	
	public ProjectService() {
		
	}
	
	/**
	 * 通过id取得项目
	 * @param projectId
	 * @return
	 */
	public CProject findByProjectId(String projectId) {
		return projectDao.queryById(projectId);
	}
	
	public CProject findByUserIdAndProjectName(String userId, String projectName) {
		return  projectDao.queryByUserIdAndProjectName(userId, projectName);
	}
	
	public boolean create(CProject cp) throws Exception {
		return projectDao.save(cp);
	}
	
	public boolean create(CProject cp, String workPath) 
			throws SecurityException, IOException {
		CProject p = projectDao.queryByUserIdAndProjectName(cp.getUser().getId(), cp.getProjectName());
		if (p != null) {
			throw new ApplicationException("The \"" + cp.getProjectName() + "\" project already is exist!");
		}
		if (!fs.createFolder(workPath, cp.getProjectName())) {
			throw new ApplicationException("Failed to create the \"" + cp.getProjectName() + "\" project!");
		}
		
		if (!projectDao.save(cp)) {
			fs.delete(workPath + "/" + cp.getProjectName());
			throw new ApplicationException("Failed to create the \"" + cp.getProjectName() + "\" project!");
		}
		if ("java".equals(cp.getProjectType())) {
			//compileProject.exeBuild(cp.getUser().getWorkPath() + '/' + cp.getProjectName(), Project.MSG_INFO);
			fs.createFolder(workPath + "/" + cp.getProjectName(), "src");
			fs.createFolder(workPath + "/" + cp.getProjectName(), "classes");
		}
		return true;
	}
	
	public boolean updateProjectStatus(String userId, String[] projectIds, boolean status) {
		return projectDao.updateProjectStatus(userId, projectIds, status);
	}
	
	public boolean renameProject(CProject p, String path, String newName) {
		boolean bool = true;
		try {
			projectDao.update(p);
			bool = fs.renameFile(path, newName);
		} catch(Exception e) {
			e.printStackTrace();
			bool = false;
		}
		
		return bool;
	}
	
	public void deleteProject(CProject cp) throws Exception {
		projectDao.delete(cp);
	}
	
	/**
	 * 当第一次请求的时候只显示项目树，从数据库获取
	 * @param user
	 * @param projectName
	 * @return
	 */
	public List<TreeNode> getList(UserVOBean user) {
		/*ArrayList<TreeNode> fileList = new ArrayList<TreeNode>();
		File dir = new File(user.getWorkPath()); 
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
        	String fileName = files[i].getName();
        	fileList.add(new TreeNode(fileName, "", false));
        }*/
		List<CProject> projectList = projectDao.queryForClosedProjectsByUserId(user.getId());
		ArrayList<TreeNode> treeNodeList = new ArrayList<TreeNode>();
		for (CProject cproject :  projectList) {
        	TreeNode treeNode = new TreeNode(cproject.getId(), cproject.getProjectName(), "", false, cproject.getProjectType());
        	treeNodeList.add(treeNode);
        }
		return treeNodeList;
	}
	
	/**
	 * 取得项目列表，从磁盘上面取
	 * @param user
	 * @param projectName
	 * @return
	 */
	public List<TreeNode> getList(String workPath) {
		ArrayList<TreeNode> fileList = new ArrayList<TreeNode>();
		File dir = new File(workPath); 
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
        	String fileName = files[i].getName();
        	fileList.add(new TreeNode(fileName, null, false));
        }
        
        return fileList;
	}
	
	/**
	 * 取得项目的详细信息
	 * @param userId
	 * @return
	 */
	public List<CProject> getClosedProjectList(String userId, Page page) {
		return projectDao.queryForClosedProjectsByUserId(userId, page);
	}
	
	/**
	 * 取得每个项目的子文件
	 * @param user
	 * @param projectName
	 * @return
	 */
	public List<TreeNode> getChildrenList(String projectPath) {
		ArrayList<TreeNode> fileList = new ArrayList<TreeNode>();
		return searchFiles(projectPath, fileList);
	}
	
	/**
	 * 递归遍历磁盘文件
	 * @param path
	 * @return
	 */
	protected List<TreeNode> searchFiles(String path, List<TreeNode> fileList) {
		File dir = new File(path); 
        File[] files = dir.listFiles();
        if (files == null) 
            return null; 
        for (int i = 0; i < files.length; i++) { 
            if (files[i].isDirectory()) {
            	TreeNode treeNode = new TreeNode(files[i].getName(), null, false);
            	treeNode.setChildren(new ArrayList<TreeNode>());
            	fileList.add(treeNode);
            	searchFiles(files[i].getAbsolutePath(), treeNode.getChildren()); 
            } else {
            	String fileName = files[i].getName();
            	String fileType = this.getFileType(fileName);
                fileList.add(new TreeNode(fileName, fileType, true));                    
            } 
        }
        
		return fileList;
	}
	
	protected String getFileType(String fileName) {
		String fileType = null;
		int index = fileName.lastIndexOf(".");
    	if (index != -1) {
    		fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
    		if ("doc".equals(fileType) || "docx".equals(fileType)) {
    			fileType = "doc";
    		}
    		if ("xls".equals(fileType) || "xlsx".equals(fileType)) {
    			fileType = "xls";
    		}
    		if ("ppt".equals(fileType) || "pptx".equals(fileType)) {
    			fileType = "ppt";
    		}
    	} else {
    		fileType = "empty";
    	}
		return fileType;
	}
	
	/**
	 * 编译用户程序
	 * @param workPath
	 * @param projectName
	 */
	public void build(String appPath, String userRealWorkRootPath, String projectName) throws IDEBuildException {
		new CompileProject().exeBuild(appPath, userRealWorkRootPath + "/" + projectName, Project.MSG_ERR);
	}
	
	/**
	 * 运行用户程序
	 * @param workPath
	 * @param projectName
	 */
	public void run(String appPath, String userRealWorkRootPath, String projectName, String mainClass) throws IDEBuildException {
		new CompileProject().runJavaProject(appPath, userRealWorkRootPath + "/" + projectName, mainClass, Project.MSG_ERR);
	}
	
	/*public void searchFiles(String path, StringBuffer returnStr) {
		File dir = new File(path); 
        File[] files = dir.listFiles();
        if (files == null) 
        	returnStr = null; 
        for (int i = 0; i < files.length; i++) {
        	returnStr.append("{'text':'");  
            returnStr.append(files[i].getName());
            returnStr.append("'");
            if (files[i].isDirectory()) {
            	returnStr.append(",'children':[");;
            	searchFiles(files[i].getAbsolutePath(), returnStr);
            	returnStr.append("]},"); 
            } else { 
                returnStr.append(",'leaf':true},");                      
            } 
        }
	}*/

}
